import type {Account} from "../types/Account.ts";
import {StorageUtils} from "../utils/StorageUtils.ts";
import {parseCookie} from "../network/utils/CookieUtils.ts";
import {decodeGBK} from "../network/utils/StrUtils.ts";
import {ElMessageBox} from "element-plus";

import {defineStore} from 'pinia'
import {NgaApi} from "../network/api/NgaApi.ts";

interface State {
    account: Account | undefined;
    accounts: Account[];
}

export const useAccountStore = defineStore('AccountStore', {
    state: (): State => ({
        // 当前账号
        account: undefined,
        // 账号列表
        accounts: []
    }),
    actions: {
        loadAccounts() {
            this.accounts = StorageUtils.get("accounts") as Account[] || [];
            if (this.accounts.length > 0) {
                this.account = this.accounts.find(a => a.defaultUser)
            }
            console.log('账号列表', this.accounts)
            console.log('默认账号', this.account?.username)
        },
        saveAccounts() {
            StorageUtils.put("accounts", this.accounts)
            console.log("保存账号列表", this.accounts)
        },
        removeAccount(userId: number) {
            this.accounts = this.accounts.filter(a => a.userId != userId)
            this.saveAccounts()
        },
        setDefaultAccount(userId: number) {
            this.accounts.forEach(a => a.defaultUser = a.userId == userId)
            this.saveAccounts()
        },
        addAccount(cookie: string) {
            let cookies = parseCookie(cookie);
            const ngaPassportUid = cookies.find(c => c.key == 'ngaPassportUid')?.value
            const ngaPassportUrlencodedUname = cookies.find(c => c.key == "ngaPassportUrlencodedUname")?.value!!
            const ngaPassportCid = cookies.find(c => c.key == "ngaPassportCid")?.value
            if (this.accounts.find(a => a.userId == Number(ngaPassportUid))) {
                ElMessageBox.alert(`账号已存在，用户名：${decodeGBK(decodeURIComponent(ngaPassportUrlencodedUname))}`, "提示", {
                    confirmButtonText: "确定",
                    type: "warning",
                })
                return
            }
            // 设置Cookie
            document.cookie = `ngaPassportUid=${ngaPassportUid};path=/api-${ngaPassportUid}`
            document.cookie = `ngaPassportCid=${ngaPassportCid};path=/api-${ngaPassportUid}`
            this.accounts.push({
                userId: Number(ngaPassportUid),
                username: decodeGBK(decodeURIComponent(ngaPassportUrlencodedUname))!!,
                defaultUser: this.accounts.length == 0
            })
            this.saveAccounts()
        },
    },
    getters: {
        getNgaApi: () => (): NgaApi => {
            // 如果地址栏参数存在account参数，则返回对应账号的 NgaApi, 否则使用当前账号的NgaService
            const userId = useAccountStore().getAccountUserId()
            return new NgaApi(`/api-${userId}`)
        },
        /**
         * 获取当前账号的userId
         * @param state
         */
        getAccountUserId: (state: State) => (): number => {
            const account = new URL(window.location.href).searchParams.get("account")
            const a = account ? Number(account) : undefined
            const b = state.account?.userId
            return a || b || 0
        },
    },
})

